import { _decorator, Component, Node, v3, CCInteger, AudioClip, Collider2D, Contact2DType, IPhysics2DContact, director, Director } from 'cc';
import { BulletAttr, BulletConstant } from './constant/BulletConstant';
import { Enemy } from './Enemy';
import { AudioMgr } from './tool/AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('Bullet')
export class Bullet extends Component {
    
    @property(CCInteger)
    bulletIndex: number;

    @property(AudioClip)
    shotAudio:AudioClip
    bulletAttr: BulletAttr;

    
    start() {

        this.bulletAttr = BulletConstant.bulletAttrs[this.bulletIndex]

        this.playShotAudio()

        let collider = this.node.getComponent(Collider2D)
        if(collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this)
        }

    }

    update(deltaTime: number) {
        this.go(deltaTime)
    }

    // 播放发射音乐
    playShotAudio() {
        if(AudioMgr.inst.audioSource.playing){
            AudioMgr.inst.playOneShot(this.shotAudio)
        }
    }


    go(dt:number) {

        let {x, y} = this.node.position

        this.node.setPosition(v3(x, y + dt * this.bulletAttr.speed))

        if(y > 600) {
            this.die()
        }

    }

    die() {
        this.node.destroy()
    }



    /**
     * 碰撞回调
     * @param selfCollider 当前组件
     * @param otherCollider 被碰到的组件
     * @param contact 
     */
    onBeginContact (selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {

        let enemy = otherCollider.getComponent(Enemy)

        if(selfCollider.tag == 1 && otherCollider.tag == 2 && enemy.enemyAttr.hp > 0) {
            // 击中敌人
            enemy.killed(this.bulletAttr.power)
            
            // 自己消失
            director.once(Director.EVENT_AFTER_PHYSICS, () => {
                selfCollider.getComponent(Bullet).die()
            })
        }

    }
}


